<template>
  <div>
    <el-card>
      <div class="control-box">
        <el-button
          :disabled="showShopBtn"
          class="add-shop"
          @click="addShopItem()"
          type="primary"
          >新 增</el-button
        >
        <el-dialog
          title="店铺信息"
          class="add-form"
          width="672px"
          top="152px"
          :visible.sync="dialogFormVisible"
          center
          @close="closeDialogFormVisible"
        >
          <el-form
            ref="form"
            :model="add_newShop"
            :rules="addForm"
            :label-position="labelPosition"
            label-width="200px"
          >
            <el-form-item
              ref="serial_number"
              label="编号:"
              prop="serial_number"
            >
              <el-input
                placeholder="编号"
                v-model="add_newShop.serial_number"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              ref="upload_img"
              class="upload-form-item"
              prop="upload_img"
            >
              <el-upload
                ref="picture_card"
                :class="{ hide: showBtnDealImg, inline: true }"
                :on-change="dealImgChange"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleDealImgRemove"
                :auto-upload="uploadAction"
                accept=".jpeg,.jpg,.gif,.png"
                :file-list="dealFileList"
                :limit="1"
                action=""
                list-type="picture-card"
              >
                <i slot="default" class="el-icon-plus"></i>
              </el-upload>
              <el-dialog
                custom-class="dialogImage"
                :modal="false"
                :visible.sync="dialogVisible"
              >
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
            <el-form-item ref="road_name" label="道路名称:" prop="road_name">
              <el-input
                placeholder="道路名称"
                v-model="add_newShop.road_name"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item ref="unit_adress" label="地址:" prop="unit_adress">
              <el-input
                placeholder="地址"
                v-model="add_newShop.unit_adress"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item ref="lng" label="经度:" prop="lng">
              <el-input
                placeholder="百度地图获取的经度"
                v-model="add_newShop.lng"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item ref="lat" label="纬度:" prop="lat">
              <el-input
                placeholder="百度地图获取的纬度"
                v-model="add_newShop.lat"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item>
                <iframe ref="iframeDom" class="bm-view" v-if="showMapContainer" :src="mapHtmlPath" frameborder="0" scrolling="auto"></iframe>
            </el-form-item> -->
            <el-form-item ref="detail" label="单位名称:" prop="detail">
              <el-input
                placeholder="单位名称"
                v-model="add_newShop.detail"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item ref="name" label="联系人:" prop="name">
              <el-input
                placeholder="联系人"
                v-model="add_newShop.name"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item ref="phone" label="联系电话:" prop="phone">
              <el-input
                placeholder="联系电话"
                v-model="add_newShop.phone"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item ref="categary" label="大分类:" prop="categary">
              <el-select v-model="add_newShop.categary" placeholder="大分类">
                <el-option
                  v-for="item in categary_opt"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item ref="status" label="经营业态:" prop="status">
              <el-input
                placeholder="经营业态"
                v-model="add_newShop.status"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item ref="wg" label="所属网格:" prop="wg">
              <el-select v-model="add_newShop.wg" placeholder="所属网格">
                <el-option
                  v-for="item in wg_opt"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item ref="dz_number" label="店招数:" prop="dz_number">
              <el-input
                placeholder="店招数"
                v-model="add_newShop.dz_number"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              ref="dz_affiliation"
              label="店招归属:"
              prop="dz_affiliation"
            >
              <el-select
                v-model="add_newShop.dz_affiliation"
                placeholder="店招归属"
              >
                <el-option
                  v-for="item in dz_affiliation_opt"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item ref="spec" label="店招规格:" prop="spec">
              <el-select v-model="add_newShop.spec" placeholder="店招规格">
                <el-option
                  v-for="item in spec_opt"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submit()" v-loading="loginLoading"
              >提 交</el-button
            >
          </div>
        </el-dialog>
        <el-dialog
          title="店铺信息"
          class="add-form"
          width="672px"
          top="152px"
          :visible.sync="dialogFormVisibleUpdate"
          center
          @close="closeDialogFormVisibleUpdate"
        >
          <el-form
            ref="formUpdate"
            :model="add_newShop"
            :rules="addForm"
            :label-position="labelPosition"
            label-width="200px"
          >
            <el-form-item label="编号:" prop="serial_number">
              <el-input
                placeholder="编号"
                v-model="add_newShop.serial_number"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item class="upload-form-item" prop="upload_img_update">
              <el-upload
                ref="picture_card_update"
                :class="{ hide: showBtnDealImg, inline: true }"
                :on-change="dealUpdateImgChange"
                :on-remove="handleDealUpdateImgRemove"
                :on-preview="handlePictureCardPreviewUpdate"
                :auto-upload="uploadAction"
                accept=".jpeg,.jpg,.gif,.png"
                :file-list="dealUpdateFileList"
                :limit="1"
                action=""
                list-type="picture-card"
              >
                <i slot="default" class="el-icon-plus"></i>
              </el-upload>
              <el-dialog
                custom-class="dialogImage"
                :modal="false"
                :visible.sync="dialogVisibleUpdate"
              >
                <img width="100%" :src="dialogImageUrlUpdate" alt="" />
              </el-dialog>
            </el-form-item>
            <el-form-item ref="road_name" label="道路名称:" prop="road_name">
              <el-input
                placeholder="道路名称"
                v-model="add_newShop.road_name"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="地址:" prop="unit_adress">
              <el-input
                placeholder="地址"
                v-model="add_newShop.unit_adress"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item ref="lng" label="经度:" prop="lng">
              <el-input
                placeholder="百度地图获取的经度"
                v-model="add_newShop.lng"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item ref="lat" label="纬度:" prop="lat">
              <el-input
                placeholder="百度地图获取的纬度"
                v-model="add_newShop.lat"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item>
              <iframe ref="iframeDomUpdate" class="bm-view" v-if="showMapUpdateContainer" :src="mapHtmlPath" frameborder="0" scrolling="auto"></iframe>
            </el-form-item> -->
            <el-form-item label="单位名称:" prop="detail">
              <el-input
                placeholder="单位名称"
                v-model="add_newShop.detail"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系人:" prop="name">
              <el-input
                placeholder="联系人"
                v-model="add_newShop.name"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系电话:" prop="phone">
              <el-input
                placeholder="联系电话"
                v-model="add_newShop.phone"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="大分类:" prop="categary">
              <el-select v-model="add_newShop.categary" placeholder="大分类">
                <el-option
                  v-for="item in categary_opt"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="经营业态:" prop="status">
              <el-input
                placeholder="经营业态"
                v-model="add_newShop.status"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="所属网格:" prop="wg">
              <el-select v-model="add_newShop.wg" placeholder="所属网格">
                <el-option
                  v-for="item in wg_opt"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="店招数:" prop="dz_number">
              <el-input
                placeholder="店招数"
                v-model="add_newShop.dz_number"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="店招归属:" prop="dz_affiliation">
              <el-select
                v-model="add_newShop.dz_affiliation"
                placeholder="店招归属"
              >
                <el-option
                  v-for="item in dz_affiliation_opt"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="店招规格:" prop="spec">
              <el-select v-model="add_newShop.spec" placeholder="店招规格">
                <el-option
                  v-for="item in spec_opt"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button
              type="primary"
              @click="update()"
              v-loading="updateLoginLoading"
              >提 交</el-button
            >
          </div>
        </el-dialog>
        <el-input
          v-model="sousuo"
          placeholder="请输入编号/地址/单位名称"
          prefix-icon="el-icon-search"
          style="width: 320px; float: right"
          @keyup.enter.native="searchEnterFun"
        >
        </el-input>
      </div>

      <el-table
        class="shop_list_table"
        highlight-current-row
        :cell-style="{
          textAlign: 'center',
          fontSize: '16px',
          fontFamily: 'Microsoft YaHei',
          fontWeight: '400',
          color: '#494949',
          padding: '2px 0'
        }"
        :header-cell-style="{
          textAlign: 'center',
          fontSize: '16px',
          fontFamily: 'Microsoft YaHei',
          fontWeight: 'bold',
          color: '#494949',
          background: '#F2F6FF',
          padding: '10px 0'
        }"
        :data="shopTable"
      >
        <el-table-column
          type="index"
          label="序号"
          width="60"
          show-overflow-tooltip
        >
          <template scope="scope">
            <span>{{ (currentPage - 1) * pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="serial_number"
          label="编号"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="road_name"
          label="道路名称"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column prop="unit_adress" label="地址" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="detail" label="单位名称" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="name" label="联系人" show-overflow-tooltip>
          <template scope="scope">
            <span v-if="scope.row.name ? true : false">{{
              scope.row.name
            }}</span>
            <span v-else-if="scope.row.legal_person ? true : false">{{
              scope.row.legal_person
            }}</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" show-overflow-tooltip>
          <template scope="scope">
            <span v-if="scope.row.phone ? true : false">{{
              scope.row.phone
            }}</span>
            <span v-else-if="scope.row.legal_person_phone ? true : false">{{
              scope.row.legal_person_phone
            }}</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="categary" label="大分类" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="status" label="经营业态" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="wg" label="所属网格" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="dz_number" label="店招数" show-overflow-tooltip>
        </el-table-column>
        <el-table-column
          prop="dz_affiliation"
          label="店招归属"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column prop="spec" label="店招规格" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="roomId" label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              :disabled="showShopBtn"
              type="text"
              @click="modify(scope.row)"
              >修改</el-button
            >
            <el-button
              :disabled="showShopBtn"
              type="text"
              @click="delet(scope.row)"
              >删除</el-button
            >
            <!-- <el-button type="text" @click="editCom(scope.row)">通过</el-button>
        <el-button type="text" @click="reject(scope.row)">驳回</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="prevClick"
        @next-click="nextClick"
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import {
  canvasDataURL,
  convertBase64UrlToBlob
} from "../utils/canvasBase64.js";
import qs from "qs";
//image-upload
export default {
  data() {
    let validateFileUrl = (rule, value, callback) => {
      if (this.$refs.picture_card.$children[0].files.length === 0) {
        callback(new Error("请选择图片"));
      } else {
        callback();
      }
    };
    let validateFileUrlUpdate = (rule, value, callback) => {
      if (this.$refs.picture_card_update.$children[0].files.length === 0) {
        callback(new Error("请选择图片"));
      } else {
        callback();
      }
    };
    // let validPhone = (rule, value,callback)=>{
    //   const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/
    //   if (!value){
    //     callback(new Error('请填写联系电话'))
    //   }else  if (!reg.test(value)){
    //     callback(new Error('请填写正确的11位手机号码'))
    //   }else {
    //       callback()
    //   }
    // }
    return {
      mapHtmlPath: "/bmap/demo01.html",
      iframeWin: null,
      map: null,
      geoc: null,
      showMapContainer: false,
      showMapUpdateContainer: false,
      showShopBtn: false,
      loginLoading: false,
      updateLoginLoading: false,
      uploadAction: false,
      add_newShop: {
        id: "",
        serial_number: "",
        road_name: "",
        unit_adress: "",
        lng: "",
        lat: "",
        detail: "",
        name: "",
        phone: "",
        categary: "",
        dz_number: "",
        status: "",
        wg: "",
        dz_affiliation: "",
        spec: ""
      },
      categary_opt: [
        { value: "超市", label: "超市" },
        { value: "蔬菜果品", label: "蔬菜果品" },
        { value: "餐饮", label: "餐饮" },
        { value: "杂货", label: "杂货" },
        { value: "宾馆酒店", label: "宾馆酒店" },
        { value: "其他", label: "其他" }
      ],
      wg_opt: [
        { value: "0701", label: "0701" },
        { value: "0702", label: "0702" },
        { value: "0703", label: "0703" }
      ],
      dz_affiliation_opt: [
        { value: "商户自设", label: "商户自设" },
        { value: "无店招", label: "无店招" },
        { value: "统一设置", label: "统一设置" }
      ],
      spec_opt: [
        { value: "小型", label: "小型" },
        { value: "中型", label: "中型" },
        { value: "大型", label: "大型" },
        { value: "特大型", label: "特大型" }
      ],
      labelPosition: "right",
      showBtnDealImg: false,
      dealFileList: [],
      dealUpdateFileList: [],
      limitCountImg: 1,
      addForm: {
        serial_number: [
          { required: true, message: "请填写编号", trigger: "blur" }
        ],
        upload_img: [
          { required: true, validator: validateFileUrl, trigger: "change" }
        ],
        upload_img_update: [
          {
            required: true,
            validator: validateFileUrlUpdate,
            trigger: "change"
          }
        ],
        road_name: [
          { required: true, message: "请填写道路名称", trigger: "blur" }
        ],
        unit_adress: [
          { required: true, message: "请填写地址", trigger: "blur" }
        ],
        lng: [{ required: true, message: "请填写经度", trigger: "blur" }],
        lat: [{ required: true, message: "请填写纬度", trigger: "blur" }],
        detail: [
          { required: true, message: "请填写单位名称", trigger: "blur" }
        ],
        // name: [{ required: true, message: "请填写联系人", trigger: "blur" }],
        // phone: [{validator: validPhone,  required: true, trigger: "blur" }],
        categary: [
          { required: true, message: "请填写大分类", trigger: "blur" }
        ],
        dz_number: [
          { required: true, message: "请填写店招数", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请填写经营业态", trigger: "blur" }
        ],
        wg: [{ required: true, message: "请填写所属网格", trigger: "blur" }],
        dz_affiliation: [
          { required: true, message: "请选择店招属性", trigger: "blur" }
        ],
        spec: [{ required: true, message: "请选择店招规格", trigger: "blur" }]
      },
      shopTable: [],
      shopTable1: [],
      shopTableOrigin: [],
      sousuo: "",
      dialogImageUrl: "",
      dialogVisible: false,
      dialogImageUrlUpdate: "",
      dialogVisibleUpdate: false,
      dialogFormVisible: false,
      dialogFormVisibleUpdate: false,
      total: 1,
      currentPage: 1,
      pageSize: 18
    };
  },
  created() {
    this.orderList(this.currentPage);
  },
  mounted() {
    //window.addEventListener("message",this.handleMessage)
    this.$nextTick(() => {
      let qx = this.$store.getters.getUser.user_qx;
      if (qx === "超级管理员") {
        this.showShopBtn = false;
      } else if (qx === "管理员") {
        this.showShopBtn = false;
      } else if (qx === "编辑者") {
        this.showShopBtn = false;
      } else if (qx === "查看者") {
        this.showShopBtn = true;
      }
    });
  },
  watch: {
    // sousuo(curVal) {
    //   console.log(curVal);
    //   this.loading = true;
    //   // 实现input连续输入，只发一次请求
    //   clearTimeout(this.timeout);
    //   this.timeout = setTimeout(() => {
    //     this.sousuoList(curVal);
    //   }, 2000);
    // },
    // value1(curVal) {
    //   this.shaixuan(curVal);
    // }
  },
  methods: {
    searchEnterFun(e) {
      var keyCode = window.event ? e.keyCode : e.which;
      if (keyCode == 13) {
        let s = this.sousuo;
        this.shopTable = [];
        this.$request({
          url: "/rf/getAllHpDianZhaoDianPaiInfo",
          method: "get",
          params: { key: s, page: 1 }
          //headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
        })
          .then(response => {
            if (response.error_code == 0) {
              this.currentPage = 1;
              this.total = response.count;
              this.shopTable = response.data;
            } else {
              this.$message({ message: response.error_msg, type: "info" });
            }
          })
          .catch(error => {
            this.$message({
              message: "搜索失败，网络异常",
              type: "info",
              duration: 2000
            });
          });
      }
    },
    closeDialogFormVisible() {
      this.dialogFormVisible = false;
      this.showMapContainer = false;
      this.loginLoading = false;
      this.dealFileList = [];
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      });
    },
    closeDialogFormVisibleUpdate() {
      this.dialogFormVisibleUpdate = false;
      this.showMapUpdateContainer = false;
      this.dealUpdateFileList = [];
      this.updateLoginLoading = false;
      this.$nextTick(() => {
        this.$refs.formUpdate.resetFields();
      });
    },
    addShopItem() {
      this.showMapContainer = true;
      //this.handler("container")
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        //this.iframeWin = this.$refs.iframeDom.contentWindow;
        this.$refs.form.resetFields();
        // this.$refs.serial_number.resetField();
        // this.$refs.picture_card.clearFiles();
        // this.$refs.upload_img.resetField();
        this.showBtnDealImg =
          this.$refs.picture_card.$children[0].files.length >=
          this.limitCountImg;
        // this.$refs.unit_adress.resetField();
        // this.$refs.unit_name.resetField();
        // this.$refs.name.resetField();
        // this.$refs.phone.resetField();
        // this.$refs.status.resetField();
        // this.$refs.dz_affiliation.resetField();
        // this.$refs.spec.resetField();
      });
    },
    dealImgChange(file, fileList) {
      //console.log(file, fileList.length);
      this.showBtnDealImg = fileList.length >= this.limitCountImg;
    },
    previewDealImg(file) {},
    handleDealImgRemove(file, fileList) {
      let length = fileList.length;
      this.showBtnDealImg = length >= this.limitCountImg;
    },
    dealUpdateImgChange(file, fileList) {
      console.log(file, fileList.length);
      this.showBtnDealImg = fileList.length >= this.limitCountImg;
    },
    handleDealUpdateImgSuccess(response, file, fileList) {
      console.log(file);
    },
    handleDealUpdateImgRemove(file, fileList) {
      let length = fileList.length;
      this.showBtnDealImg = length >= this.limitCountImg;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreviewUpdate(file) {
      this.dialogImageUrlUpdate = file.url;
      this.dialogVisibleUpdate = true;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.orderList(val);
    },
    prevClick(val) {
      this.orderList(val);
    },
    nextClick(val) {
      this.orderList(val);
    },
    //新增提交
    submit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.loginLoading = true;
          let formdata = new FormData();
          let {
            id,
            serial_number,
            road_name,
            unit_adress,
            lng,
            lat,
            detail,
            name,
            phone,
            categary,
            dz_number,
            status,
            wg,
            dz_affiliation,
            spec
          } = this.add_newShop;
          formdata.append("serial_number", serial_number);
          formdata.append("road_name", road_name);
          formdata.append("unit_adress", unit_adress.replace(/\s+/g, ""));
          formdata.append("lng", lng);
          formdata.append("lat", lat);
          formdata.append("detail", detail);
          formdata.append("name", name);
          formdata.append("phone", phone);
          formdata.append("categary", categary);
          formdata.append("dz_number", dz_number);
          formdata.append("status", status);
          formdata.append("wg", wg);
          formdata.append("dz_affiliation", dz_affiliation);
          formdata.append("spec", spec);
          formdata.append(
            "image",
            this.$refs.picture_card.$children[0].files[0].raw
          );

          if (
            this.$refs.picture_card.$children[0].files[0].size / 1024 >
            1025
          ) {
            this.photoCompress(
              this.$refs.picture_card.$children[0].files[0].raw,
              { quality: 0.2 },
              base64Codes => {
                let _blob = convertBase64UrlToBlob(base64Codes);
                formdata.append("image_simple", _blob);
                this.submitData(formdata);
              }
            );
          } else {
            formdata.append(
              "image_simple",
              this.$refs.picture_card.$children[0].files[0].raw
            );
            this.submitData(formdata);
          }
        } else {
          this.$message({ type: "info", message: "信息请填写完整" });
        }
      });
    },
    submitData(fdata) {
      this.$request({
        url: "/rf/addHpDianZhaoDianPaiInfo",
        method: "post",
        data: fdata,
        headers: { "Content-Type": "multipart/form-data" }
      })
        .then(response => {
          if (response.error_code == 0) {
            this.loginLoading = false;
            this.closeDialogFormVisible();
            this.$message({ type: "success", message: "添加成功" });
            this.orderList(this.currentPage);
          } else {
            this.loginLoading = false;
            this.$message({
              type: "info",
              message: response.error_msg
            });
          }
        })
        .catch(error => {
          this.loginLoading = false;
          this.$message({
            message: "提交失败，网络异常",
            type: "info",
            duration: 2000
          });
        });
    },
    getImageBlob(url) {
      var r = new XMLHttpRequest();
      r.open("GET", url, false);
      r.overrideMimeType("text/plain; charset=x-user-defined");
      r.send(null);
      var blob = binaryToBlob(r.responseText);
      blob.name = blob.fileName = url.substring(url.lastIndexOf("/") + 1);
      blob.fileType = "image/jpeg"; //"image/octet-stream";
      return blob;
    },
    //修改提交
    update() {
      this.$refs.formUpdate.validate(async valid => {
        if (valid) {
          this.updateLoginLoading = true;
          let formdata = new FormData();
          console.log(this.add_newShop);
          let {
            id,
            serial_number,
            road_name,
            unit_adress,
            lng,
            lat,
            detail,
            name,
            phone,
            categary,
            dz_number,
            status,
            wg,
            dz_affiliation,
            spec
          } = this.add_newShop;

          formdata.append("id", id);
          formdata.append("serial_number", serial_number);
          formdata.append("road_name", road_name);
          formdata.append("unit_adress", unit_adress.replace(/\s+/g, ""));
          formdata.append("lng", lng);
          formdata.append("lat", lat);
          formdata.append("detail", detail);
          formdata.append("name", name);
          formdata.append("phone", phone);
          formdata.append("categary", categary);
          formdata.append("dz_number", dz_number);
          formdata.append("status", status);
          formdata.append("wg", wg);
          formdata.append("dz_affiliation", dz_affiliation);
          formdata.append("spec", spec);

          if (this.$refs.picture_card_update.$children[0].files[0].raw) {
            formdata.append(
              "image",
              this.$refs.picture_card_update.$children[0].files[0].raw
            );
            if (
              this.$refs.picture_card_update.$children[0].files[0].size / 1024 >
              1025
            ) {
              this.photoCompress(
                this.$refs.picture_card_update.$children[0].files[0].raw,
                { quality: 0.2 },
                base64Codes => {
                  let _blob = convertBase64UrlToBlob(base64Codes);
                  formdata.append("image_simple", _blob);
                  this.submitUpdateData(formdata);
                }
              );
            } else {
              formdata.append(
                "image_simple",
                this.$refs.picture_card_update.$children[0].files[0].raw
              );
              this.submitUpdateData(formdata);
            }
          } else {
            this.submitUpdateData(formdata);
          }
        } else {
          this.$message({ type: "info", message: "信息请填写完整" });
        }
      });
    },
    submitUpdateData(fdata) {
      this.$request({
        url: "/rf/updateHpDianZhaoDianPaiInfo",
        method: "post",
        data: fdata,
        headers: { "Content-Type": "multipart/form-data" }
      })
        .then(response => {
          if (response.error_code == 0) {
            this.updateLoginLoading = false;
            this.closeDialogFormVisibleUpdate();
            this.$message({ type: "success", message: "修改成功" });
            this.orderList(this.currentPage);
          } else {
            this.updateLoginLoading = false;
            this.$message({
              type: "info",
              message: response.error_msg
            });
          }
        })
        .catch(error => {
          this.updateLoginLoading = false;
          this.$message({
            message: "提交失败，网络异常",
            type: "info",
            duration: 2000
          });
        });
    },
    photoCompress(file, w, objDiv) {
      this.ready = new FileReader();
      this.ready.readAsDataURL(file);
      this.ready.onload = () => {
        let re = this.ready.result;
        canvasDataURL(re, w, objDiv);
      };
    },
    orderList(page) {
      let s = this.sousuo;
      this.shopTable = [];
      this.$request({
        url: "/rf/getAllHpDianZhaoDianPaiInfo",
        method: "get",
        params: { key: s, page: page }
      })
        .then(response => {
          if (response.error_code == 0) {
            this.total = response.count;
            this.shopTable = response.data;
          } else {
            this.$message({ message: response.error_msg, type: "info" });
          }
        })
        .catch(error => {
          this.$message({
            message: "查询失败，网络异常",
            type: "info",
            duration: 2000
          });
        });
    },
    modify(row) {
      this.showMapUpdateContainer = true;
      this.dialogFormVisibleUpdate = true;
      this.dealUpdateFileList = [];
      this.dealUpdateFileList.push({
        name: "",
        url: row.imageurl + "?r=" + Math.random()
      });
      this.$nextTick(() => {
        // this.iframeWin = this.$refs.iframeDomUpdate.contentWindow;
        // this.iframeWin.onload = ()=>{
        //   this.sendMessage(row);
        // }
        this.add_newShop = { ...row };
        //console.log(this.$refs.picture_card_update.$children[0].files)
        this.showBtnDealImg =
          this.$refs.picture_card_update.$children[0].files.length >=
          this.limitCountImg;
      });
    },
    delet(row) {
      this.$confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          this.$request({
            url: "/rf/deleteHpDianZhaoDianPaiInfo",
            method: "post",
            data: qs.stringify({ id: row.id })
          })
            .then(response => {
              if (response.error_code == 0) {
                this.$message({ type: "success", message: "删除成功" });
                if (this.shopTable.length !== 1) {
                  this.orderList(this.currentPage);
                } else {
                  let cpage = this.currentPage - 1;
                  if (cpage > 0) {
                    this.orderList(cpage);
                  } else {
                    this.orderList(1);
                  }
                }
              } else {
                this.$message({ type: "success", message: response.error_msg });
              }
            })
            .catch(error => {
              this.$message({
                message: "删除失败，网络异常",
                type: "info",
                duration: 2000
              });
            });
        })
        .catch(() => {});
    },
    handler(id, px, py) {
      this.$nextTick(() => {
        var outputPath = "tiles/"; //地图瓦片所在的文件夹
        var fromat = ".jpg"; //格式

        var tileLayer = new BMap.TileLayer({
          isTransparentPng: true
        });
        tileLayer.getTilesUrl = function(tileCoord, zoom) {
          var x = tileCoord.x;
          var y = tileCoord.y;
          return outputPath + zoom + "/" + x + "/" + y + fromat;
        };

        //var map = new BMap.Map('container');

        var map = (this.map = new window.BMap.Map(id, {
          minZoom: 19,
          maxZoom: 15
        }));
        map.addTileLayer(tileLayer);
        var geoc = (this.geoc = new window.BMap.Geocoder());
        var point = new window.BMap.Point(121.492666, 31.220984);
        map.centerAndZoom(point, 15);
        map.setMinZoom(0);
        map.enableScrollWheelZoom(); //启用滚轮放大缩小
        map.enableKeyboard(); //启用键盘操作，默认禁用。键盘的上、下、左、右键可连续移动地图。
        map.enableContinuousZoom(); //启用连续缩放效果
        if (px && py) {
          var init_point = new window.BMap.Point(px, py);
          var init_marker = new window.BMap.Marker(init_point);
          map.addOverlay(init_marker);
          init_marker.enableDragging();
          init_marker.addEventListener("dragend", e => {
            this.add_newShop.lng = e.point.lng;
            this.add_newShop.lat = e.point.lat;
          });
        }

        map.addEventListener("click", e => {
          map.clearOverlays();
          //console.log('换位置百度的经度:'+e.point.lng+' , 纬度: '+e.point.lat);
          var point = new window.BMap.Point(e.point.lng, e.point.lat);
          var marker = new window.BMap.Marker(point);
          map.addOverlay(marker);
          marker.enableDragging();
          this.add_newShop.lng = e.point.lng;
          this.add_newShop.lat = e.point.lat;

          marker.addEventListener("dragend", e => {
            //console.log('换位置百度的经度:'+e.point.lng+' , 纬度: '+e.point.lat);
            this.add_newShop.lng = e.point.lng;
            this.add_newShop.lat = e.point.lat;
          });
        });
      });
    },
    searchLocation() {
      //var geoc = this.geoc = new window.BMap.Geocoder();
      console.log(this.geoc);
      console.log(this.add_newShop.unit_adress);

      this.geoc.getPoint(
        this.add_newShop.unit_adress,
        point => {
          console.log(point);
          if (point) {
            //this.map.clearOverlays();
            // var search_point = new window.BMap.Point(point.lng, point.lat);
            // var search_marker = new window.BMap.Marker(search_point);
            // this.map.addOverlay(search_marker);
            // this.map.centerAndZoom(search_point,18);
            // search_marker.enableDragging();
            this.add_newShop.lng = point.lng;
            this.add_newShop.lat = point.lat;
            // search_marker.addEventListener("dragend", (e) => {
            //   this.add_newShop.lng = e.point.lng;
            //   this.add_newShop.lat = e.point.lat;
            // });
          }
        },
        "上海市黄浦区"
      );
    },
    sendMessage(msg) {
      console.log(msg);
      console.log(this.iframeWin);
      this.iframeWin.postMessage(
        {
          cmd: "setPoint",
          params: msg
        },
        "*"
      );
    },
    handleMessage(event) {
      const { cmd, params } = event.data;
      switch (cmd) {
        case "getPoint":
          this.add_newShop.lng = params.lng;
          this.add_newShop.lat = params.lat;
          break;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.el-card__body {
  .control-box {
    display: flex;
    justify-content: space-between;
    .add-shop {
      width: 92px;
      height: 32px;
      border: 1px solid #a6e8fb;
      box-shadow: 0px 0px 1px 0px #2baaeb;
      border-radius: 6px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    /deep/.el-button {
      span {
        font-size: 20px;
      }
    }
    /deep/.add-form {
      .el-dialog {
        margin-right: 460px;

        &.dialogImage {
          margin-right: 340px;
          .el-dialog__body {
            padding-top: 30px;
            padding-left: 16px;
            padding-right: 16px;
            padding-bottom: 30px;
          }
        }
        .el-dialog__header {
          .el-dialog__title {
            font-size: 26px;
            font-family: Microsoft YaHei;
            font-weight: bold;
            color: #202020;
          }
        }
        .el-dialog__body {
          // height:400px;
          // overflow-y: scroll;
          padding-top: 50px;
          padding-left: 16px;
          padding-right: 16px;
          padding-bottom: 24px;

          .el-form {
            .el-form-item {
              .el-form-item__label {
                font-size: 20px;
                font-family: Microsoft YaHei;
                font-weight: 400;
                color: #3a4262;
              }
              .el-form-item__content {
                .el-input {
                  width: 350px;
                  height: 36px;
                  background: #fafcfd;
                }
              }
            }
            .upload-form-item {
              .el-form-item__content {
                .image-upload {
                  display: inline-block;
                  margin-right: 15px;
                }
                // .uoloadSty .el-upload--picture-card{
                //   width:110px;
                //   height:110px;
                //   line-height:110px;
                //   display: inline-block;
                //   margin-right:15px;
                // }
                .inline {
                  display: inline-block;
                  margin-right: 15px;
                }
                .hide .el-upload--picture-card {
                  display: none; /* 上传按钮隐藏 */
                }
                .hide2 .el-upload--picture-card {
                  display: none; /* 上传按钮隐藏 */
                }
              }
            }
          }
        }
      }
    }
  }
  .shop_list_table {
    margin-top: 17px;
  }
  .el-pagination {
    margin-top: 10px;
    margin-bottom: 10px;
  }
  .el-button {
    font-size: 16px;
  }
}
.errorInfo {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 100%;
  left: 0;
}

.bm-view {
  width: 100%;
  height: 300px;
}
</style>
